package com.hardydou.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import java.io.InputStream;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020/6/4
 * @Copyright ：Hardydou.com
 */
public class RegionUtil {

    private static Log logger = LogFactory.get(RegionUtil.class);
    static DbSearcher _searcher;

    static {
        try {
            InputStream in = RegionUtil.class.getResourceAsStream("/ip2region.db");
            _searcher = new DbSearcher(new DbConfig(), IoUtil.readBytes(in));
        } catch (Exception e) {
            logger.error(e);
        }
    }

    public static String getRegion(String ip) {
        try {
            DataBlock r = _searcher.memorySearch(ip);
            return r.getRegion();
        } catch (Exception e) {
            logger.error(e);
            return "";
        }
    }

}
